#!/bin/bash
echo " "
echo "==============  拉取更新并部署  ==============="
echo "  "
echo "[1/3] 拉取代码更新"
sleep 2
project_dir="/usr/www/https"
echo "  进入https目录：$project_dir"
cd "$project_dir" || { echo "  错误：无法进入目录 $project_dir！"; exit 1; }

echo "  检查Git 凭证"
git config --global credential.helper store

echo "  拉取更新：git pull origin master"
git pull origin master

echo "  "
echo "[2/3] 复制key/cer文件到nginx目录"
sleep 2
file_key="/usr/www/https/xixiyue.key"
file_cer="/usr/www/https/xixiyue.cer"
echo "  pull路径：/usr/www/https"


# 检查源文件是否存在
if [ ! -f "$file_key" ]; then
    echo "  错误：$source_file 不存在！"
    echo "  "
    exit 1
fi

if [ ! -f "$file_cer" ]; then
    echo "  错误：$source_file 不存在！"
    echo "  "
    exit 1
fi


# 设置目标目录
target_dir="/etc/nginx/"
echo "  nginx目录：/etc/nginx/"

# 检查目标目录是否存在
if [ ! -d "$target_dir" ]; then
    echo "  错误：nginx目录 $target_dir 不存在！"
    echo "  "
    exit 1
fi

# 复制文件
echo "  将key/cer复制到nginx目录"
cp -f "$file_key" "$target_dir"
cp -f "$file_cer" "$target_dir"

# 检查复制是否成功
if [ $? -eq 0 ]; then
    echo "  复制成功！"
else
    echo "  复制失败！"
    exit 1
fi

echo "  "
echo "[3/3] 重启Nginx服务"
sleep 2
echo "  进入 Nginx 目录：$target_dir"
cd "$target_dir"

echo "  重启 Nginx 服务..."
systemctl restart nginx

# 检查 Nginx 是否重启成功
if [ $? -eq 0 ]; then
    echo "  Nginx 重启成功！"
else
    echo "  Nginx 重启失败！"
    echo "  "
    exit 1
fi


echo "  重启完成，返回工作目录：/usr/www/https"
echo "  "
cd /usr/www/htpps

echo "==============  Nginx 重启完成  ==============="
echo "  "
